package com.thread.interrupt;

/**
 * <p>
 * 1. Runnabale
 *
 * 线程处在Runnable阶段时
 *      中断线程：只会设置中断标志位，不会有其它任务作用
 *      所以在线程执行过程中应该在合适的位置检查线程是否中断（检查方法：isInterrupted()）
 * </p>
 *
 * @author qingshan
 * @since 2020-09-22 08:56
 */
public class InterruptRunnableDemo1 extends Thread{
    @Override
    public void run() {
        int i = 0;
        while (!Thread.currentThread().isInterrupted()) {
            // ... 单次循环代码
            try {
                /*
                线程处在休眠状态中的话，设置中断标志位会出现异常
                此时线程也不会被标记中断
                 */
                System.out.println("thread sleep start -----" + i);
                Thread.sleep(1000);
                System.out.println("thread sleep end =====" + i++);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        }
        System.out.println("done ");
    }

    public static void main(String[] args) throws InterruptedException {
        Thread thread = new InterruptRunnableDemo1();
        thread.start();
        Thread.sleep(1000);
        System.out.println("thread is interrupted :" + thread.isInterrupted());
        // 设置线程中断标志位
        thread.interrupt();
        System.out.println("thread is end  interrupted :" + thread.isInterrupted());
    }
}
